package ai.weed.qrcode.controller;

import ai.weed.qrcode.common.Response;
import ai.weed.qrcode.domain.dto.LoginDto;
import ai.weed.qrcode.domain.LoginResponse;
import ai.weed.qrcode.domain.WxUser;
import ai.weed.qrcode.service.WxService;
import ai.weed.qrcode.service.WxUserService;
import ai.weed.qrcode.util.JwtUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * 微信登录
 *
 * @author zhong.wang
 * @date 2025/10/30
 **/
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Autowired
    private WxService wxService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private WxUserService userService;

    // 你在微信后台配置的 Token
    private static final String TOKEN = "woshidijiaaoteman";

    @PostMapping("/login")
    public Response<LoginResponse> login(@RequestBody LoginDto request) throws Exception {
        JsonNode result = wxService.login(request.getCode());

        if (result.has("errcode")) {
            throw new RuntimeException("微信登录失败: " + result.get("errmsg").asText());
        }

        String openid = result.get("openid").asText();
        String sessionKey = result.get("session_key").asText(); // 可用于后续解密用户信息

        // 创建或获取用户
        WxUser user = userService.getByOpenid(openid);
        if (user == null) {
            user = new WxUser();
            user.setOpenid(openid);
            userService.save(user);
        }

        // 生成 Token
        String token = jwtUtil.generateToken(openid);
        String refreshToken = jwtUtil.generateRefreshToken(openid);

        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setRefreshToken(refreshToken);
        response.setExpires(jwtUtil.getExpirationTime(token));
        return Response.success(response);
    }

    @PostMapping("/refreshToken")
    public Response<LoginResponse> refreshToken(@RequestHeader("Refresh-Token") String refreshToken) {
        if (!jwtUtil.validateToken(refreshToken)) {
            throw new RuntimeException("无效的刷新 Token");
        }

        String openid = jwtUtil.getOpenidFromToken(refreshToken);
        String newToken = jwtUtil.generateToken(openid);
        String newRefreshToken = jwtUtil.generateRefreshToken(openid);

        LoginResponse response = new LoginResponse();
        response.setToken(newToken);
        response.setRefreshToken(newRefreshToken);
        response.setExpires(jwtUtil.getExpirationTime(newToken));

        return Response.success(response);
    }


    /**
     * 验证签名
     */
    private boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] arr = new String[]{TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (String s : arr) {
            content.append(s);
        }
        String tmpStr = DigestUtil.sha1Hex(content.toString());
        return tmpStr.equals(signature);
    }

    @RequestMapping(value = "/wechat/message")
    @ResponseBody
    public String get(HttpServletRequest request, String signature, String timestamp, String nonce, String echostr) {
        if(request.getMethod().equalsIgnoreCase("get")){//用来校验，一般会验证前端配置的token等，这里简化了代码。
            return echostr;
        }else if(request.getMethod().equalsIgnoreCase("POST")){//接收用户的相关行为事件结果
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                StringBuilder requestContent = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    requestContent.append(line);
                }
                reader.close();
                //接收：{"ToUserName":"gh_ea84a199bf81","FromUserName":"oG0NJ5Oi_3Dd1HlZJ14xfnA0sJ6s","CreateTime":1686131943,"MsgType":"event","Event":"subscribe_msg_popup_event","List":{"PopupScene":"0","SubscribeStatusString":"accept","TemplateId":"4ondVRxk4L20ihrJ3iI15BDK72XatGPxE0MeCVwHasQ"}}
                log.info("接收：" + requestContent.toString());
                return "";
            } catch (IOException e) {
                // 处理异常情况
                e.printStackTrace();
                log.error("异常：" + e.getMessage());
                return e.toString();
            }
        }else{
            log.info("不是get 或 post方法");
            return null;
        }
    }

}
